package yuan.consumer;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.consumer.OffsetAndMetadata;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.errors.WakeupException;

import java.time.Duration;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @version: 1.0
 * @Description: TODO
 * @author: zZmH
 * @date: 2020/09/09 01:54
 */


public class ConsumerAsync {

    public static final AtomicBoolean isRunning = new AtomicBoolean(true);


    public static void main(String[] args) {
        final Properties prop = KafkaConsumerAnalysis.init();
        final KafkaConsumer<String, String> consumer = new KafkaConsumer<>(prop);
        consumer.subscribe(Arrays.asList("topic-demo"));

        try {
            while (isRunning.get()) {

                final ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
                for (TopicPartition partition : records.partitions()) {
                    final List<ConsumerRecord<String, String>> partitionRecords = records.records(partition);
                    for (ConsumerRecord<String, String> recordz : partitionRecords) {
                        System.out.println(recordz);

                    }

                    consumer.commitAsync((map, exception) -> {
                        for (Map.Entry<TopicPartition, OffsetAndMetadata> entry : map.entrySet()) {
                            System.out.format("key: %s  value: %s\n", entry.getKey(), entry.getValue());
                        }
                    });


                }


            }
        } catch (WakeupException e) {


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                consumer.commitSync();
            } finally {
                consumer.close();
            }
        }
    }

}
